package freespiritsocial.io.user.ui.adapter.search

import com.scwang.smart.refresh.layout.util.SmartUtil
import freespiritsocial.io.user.data.model.bean.SearchPojo
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.viewmodel.SearchViewModel

/**
 * 搜索子列表代理
 * @property mViewModel SearchViewModel
 * @property spaceItemDecoration SpaceItemDecoration
 * @constructor
 */
class SearchDelegate(val tag: Int,val mViewModel: SearchViewModel): ISearchAdapter {
    //统一得分割线
    override val spaceItemDecoration: SpaceItemDecoration
        get() = SpaceItemDecoration(
            SmartUtil.dp2px(5f),
            0,
            firstDim = SmartUtil.dp2px(20f)
        )

    //获取子列表适配器
    override fun getImageAdapter(item: SearchPojo) =
        ImagesAdapter(item.invitationList?.mapTo(arrayListOf()) { it.cover ?: "" } ?: arrayListOf()).apply {
            //侧滑加载更多
            loadMoreModule.setOnLoadMoreListener {
                val lastId = item.invitationList?.last()?.invitationId ?: return@setOnLoadMoreListener
                mViewModel.loadMoreSearchItemList(
                    tag,
                    lastId,
                    item.content,
                    item.searchPeoplePojo?.userId,
                    item.tagId
                ) { list ->
                    item.invitationList.addAll(list)
                    addData(list.map { it.cover ?: "" })
                    val size = item.invitationList.size
                    loadMoreModule.isEnableLoadMore = size > 0 && size % 5 == 0
                }
                loadMoreModule.loadMoreComplete()
                loadMoreModule.isEnableLoadMore = false
            }
            val size = item.invitationList?.size ?: 0
            loadMoreModule.isEnableLoadMore = size > 0 && size % 5 == 0
            setOnItemClickListener { _,_,position ->
                val invitationList = item.invitationList ?: return@setOnItemClickListener
                mViewModel.getPost(invitationList[position].invitationId)
            }
        }

}